﻿using log4net;
using MySql.Data.MySqlClient;
using Quartz;
using Quartz.Impl;

namespace FZRD
{
    public class QuartzTask
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(QuartzTask));

        private static IScheduler? dailyTaskScheduler;
        private static IScheduler? weeklyTaskScheduler;
        private static IScheduler? monthlyTaskScheduler;

        public static string connStr = "";

        //每日定时执行任务
        public static async Task DailyTask(string connDbStr, int hour, int min)
        {
            connStr = connDbStr.Trim();
            try
            {
                ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
                dailyTaskScheduler = await schedulerFactory.GetScheduler();
                await dailyTaskScheduler.Start();

                IJobDetail dailyJob = JobBuilder.Create<DailyJob>()
                    .WithIdentity("dailyJob", "group1")
                    .Build();

                ITrigger dailyTrigger = TriggerBuilder.Create()
                    .WithIdentity("dailyTrigger", "group1")
                    .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(hour, min)) // 每天午夜执行
                    .Build();

                await dailyTaskScheduler.ScheduleJob(dailyJob, dailyTrigger);
            }
            catch(Exception ex) {
                log.Error(ex.Message);
            }
            log.Info("Quartz每日任务已设置，将在每天某时某分执行");
        }

        public static async Task CancelDailyTask()
        {
            if (dailyTaskScheduler == null) { return; }
            try
            {
                await dailyTaskScheduler.Shutdown();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        //每周定时执行任务
        public static async Task WeeklyTask(string connDbStr, int week, int hour, int min)
        {
            connStr = connDbStr.Trim();
            try
            {
                ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
                weeklyTaskScheduler = await schedulerFactory.GetScheduler();
                await weeklyTaskScheduler.Start();

                IJobDetail weeklyJob = JobBuilder.Create<WeeklyJob>()
                    .WithIdentity("weeklyJob", "group2")
                    .Build();

                DayOfWeek[] dayOfWeeks = new DayOfWeek[1];
                if (week == 0)
                {
                    dayOfWeeks[0] = DayOfWeek.Sunday;
                }
                else if (week == 1)
                {
                    dayOfWeeks[0] = DayOfWeek.Monday;
                }
                else if (week == 2)
                {
                    dayOfWeeks[0] = DayOfWeek.Tuesday;
                }
                else if (week == 3)
                {
                    dayOfWeeks[0] = DayOfWeek.Wednesday;
                }
                else if (week == 4)
                {
                    dayOfWeeks[0] = DayOfWeek.Thursday;
                }
                else if (week == 5)
                {
                    dayOfWeeks[0] = DayOfWeek.Friday;
                }
                else if (week == 6)
                {
                    dayOfWeeks[0] = DayOfWeek.Saturday;
                }

                ITrigger weeklyTrigger = TriggerBuilder.Create()
                        .WithIdentity("weeklyTrigger", "group2")
                        .WithSchedule(CronScheduleBuilder.AtHourAndMinuteOnGivenDaysOfWeek(hour, min, dayOfWeeks))
                        .Build();

                await weeklyTaskScheduler.ScheduleJob(weeklyJob, weeklyTrigger);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            log.Info("Quartz每周任务已设置，将在每周的某天某时某分执行");

        }

        public static async Task CancelWeeklyTask()
        {
            if (weeklyTaskScheduler == null) { return; }
            try
            {
                await weeklyTaskScheduler.Shutdown();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }


        //每月定时执行任务
        public static async Task MonthlyTask(string connDbStr, int day, int hour, int min)
        {
            connStr = connDbStr.Trim();
            try
            {
                ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
                monthlyTaskScheduler = await schedulerFactory.GetScheduler();
                await monthlyTaskScheduler.Start();

                IJobDetail monthlyJob = JobBuilder.Create<MonthlyJob>()
                    .WithIdentity("monthlyJob", "group3")
                    .Build();

                ITrigger monthlyTrigger = TriggerBuilder.Create()
                        .WithIdentity("monthlyTrigger", "group3")
                        .WithSchedule(CronScheduleBuilder.MonthlyOnDayAndHourAndMinute(day, hour, min))
                        .Build();

                await monthlyTaskScheduler.ScheduleJob(monthlyJob, monthlyTrigger);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            log.Info("Quartz每月任务已设置，将在每月的某天某时某分执行");

        }

        public static async Task CancelMonthlyTask()
        {
            if (monthlyTaskScheduler == null) { return; }
            try
            {
                await monthlyTaskScheduler.Shutdown();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        public static async Task RestoreDatabase(string connDbStr, string backupFilePath)
        {
            connStr = connDbStr.Trim();
            try
            {
                using (MySqlConnection mysqlConn = new MySqlConnection(connDbStr.ToLower()))
                {
                    mysqlConn.Open();
                    MySqlCommand mysqlCommand = new MySqlCommand();
                    mysqlCommand.Connection = mysqlConn;
                    // 创建还原实例
                    MySqlBackup mysqlBackup = new MySqlBackup(mysqlCommand);
                    // 从文件导入数据
                    mysqlBackup.ImportFromFile(backupFilePath);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

    }

    public class DailyJob : IJob
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(DailyJob));

        public async Task Execute(IJobExecutionContext context)
        {
            log.Info($"每日任务执行时间: {DateTime.Now}");
            await PerformDailyTask();
        }

        private async Task PerformDailyTask()
        {
            log.Info("正在执行每日任务...");
            try
            {
                using (MySqlConnection mysqlConn = new MySqlConnection(QuartzTask.connStr.ToLower()))
                {
                    mysqlConn.Open();
                    MySqlCommand mysqlCommand = new MySqlCommand();
                    mysqlCommand.Connection = mysqlConn;
                    // 创建备份实例
                    MySqlBackup mysqlBackup = new MySqlBackup(mysqlCommand);
                    string outpupFilePath = Page7.getBackupFilePath() + "fzrd-" + DateTime.Now.ToString("yyyyMMdd") + ".sql";
                    // 执行备份并保存到文件
                    mysqlBackup.ExportToFile(outpupFilePath);
                    log.Info("执行备份并保存到文件:" + outpupFilePath);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
    }

    public class WeeklyJob : IJob
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(WeeklyJob));
        public async Task Execute(IJobExecutionContext context)
        {
            log.Info($"每周任务执行时间: {DateTime.Now}");
            await PerformWeeklyTask();
        }

        private async Task PerformWeeklyTask()
        {
            log.Info("正在执行每周任务...");
            try
            {
                using (MySqlConnection mysqlConn = new MySqlConnection(QuartzTask.connStr.ToLower()))
                {
                    mysqlConn.Open();
                    MySqlCommand mysqlCommand = new MySqlCommand();
                    mysqlCommand.Connection = mysqlConn;
                    // 创建备份实例
                    MySqlBackup mysqlBackup = new MySqlBackup(mysqlCommand);
                    string outpupFilePath = Page7.getBackupFilePath() + "fzrd-" + DateTime.Now.ToString("yyyyMMdd") + ".sql";
                    // 执行备份并保存到文件
                    mysqlBackup.ExportToFile(outpupFilePath);
                    log.Info("执行备份并保存到文件:" + outpupFilePath);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
    }

    public class MonthlyJob : IJob
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(MonthlyJob));
        public async Task Execute(IJobExecutionContext context)
        {
            log.Info($"每月任务执行时间: {DateTime.Now}");
            await PerformMonthlyTask();
        }

        private async Task PerformMonthlyTask()
        {
            log.Info("正在执行每月任务...");
            try
            {
                using (MySqlConnection mysqlConn = new MySqlConnection(QuartzTask.connStr.ToLower()))
                {
                    mysqlConn.Open();
                    MySqlCommand mysqlCommand = new MySqlCommand();
                    mysqlCommand.Connection = mysqlConn;
                    // 创建备份实例
                    MySqlBackup mysqlBackup = new MySqlBackup(mysqlCommand);
                    string outpupFilePath = Page7.getBackupFilePath() + "fzrd-" + DateTime.Now.ToString("yyyyMMdd") + ".sql";
                    // 执行备份并保存到文件
                    mysqlBackup.ExportToFile(outpupFilePath);
                    log.Info("执行备份并保存到文件:" + outpupFilePath);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
    }

}
